package com.wuyan.locationdog.ui.map


import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.Polygon
import com.amap.api.maps.model.PolygonOptions
import com.arcsoft.commonbase.base.BaseBindingFragment
import com.arcsoft.commonbase.bean.DeviceBeanContent
import com.arcsoft.commonbase.bean.PointBean
import com.arcsoft.commonbase.bean.TeamDetail
import com.arcsoft.commonbase.bus.Bus
import com.arcsoft.commonbase.bus.bus_device_info_modify
import com.arcsoft.commonbase.bus.bus_fence_refresh
import com.arcsoft.commonbase.bus.bus_mark_refresh
import com.arcsoft.commonbase.bus.bus_team_click
import com.arcsoft.commonbase.bus.bus_team_refresh
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.invisible
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.arcsoft.commonbase.ext.visible
import com.arcsoft.commonbase.ext.visibleOrGone
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.SpanUtils
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.wuyan.locationdog.R
import com.wuyan.locationdog.databinding.MapDeviceActivityBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.help.LoginHelp
import com.wuyan.locationdog.help.directRotation
import com.wuyan.locationdog.help.getKmOrM
import com.wuyan.locationdog.help.gpsSignalImg
import com.wuyan.locationdog.help.gpsSignalText
import com.wuyan.locationdog.help.powerImg
import com.wuyan.locationdog.ui.device.DeviceFenceListActivity
import com.wuyan.locationdog.ui.device.DeviceSetActivity
import com.wuyan.locationdog.ui.device.FlowDetailActivity
import com.wuyan.locationdog.ui.device.MapDeviceDetailActivity
import com.wuyan.locationdog.ui.device.ModeSetListActivity
import com.wuyan.locationdog.ui.device.ServiceDetailActivity
import com.wuyan.locationdog.ui.device.TrackQueryActivity
import com.wuyan.locationdog.ui.device.VoiceActivity
import com.wuyan.locationdog.ui.msg.MsgActivity
import com.wuyan.locationdog.ui.my.MarkListActivity
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.util.maputil.setDeviceDetailStatus
import com.wuyan.locationdog.view.MapPopup
import com.wuyan.locationdog.view.MapSelectPopup
import com.wuyan.locationdog.view.TeamListPopup
import com.wuyan.locationdog.view.TimeSelectPopup
import com.wuyan.locationdog.view.TipPopup
import com.wuyan.locationdog.view.TipPopup2
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import com.wuyan.locationdog.viewmodel.MsgViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.jessyan.autosize.internal.CancelAdapt
import me.jessyan.autosize.internal.CustomAdapt
import kotlin.math.log


class DeviceDetailFragment : BaseBindingFragment<MapDeviceActivityBinding>() {
    private var mapLifecycle: MapLifecycle? = null
    private var behavior: BottomSheetBehavior<LinearLayout>? = null
    var loopPosition: Int = 0
    var personDogAndAll: Int = 2
    var teamId: String = ""

    var markPointList: MutableList<PointBean>? = null


    private var phonelatLng: LatLng? = null
    private var deviceListBean: MutableList<DeviceBeanContent>? = null
    private var teamList: MutableList<TeamDetail>? = null
    val markerOptions = mutableListOf<MarkerOptions>()
    val markerOptionsTitle = mutableListOf<MarkerOptions>()

    val latLngs: MutableList<LatLng> = ArrayList()
    var isFenceClick: Boolean = true

    var isFenceChecked: Boolean = true
    var showName: Boolean = true
    var showMarkPoint: Boolean = true


    val markPointMarker: MutableList<Marker> = ArrayList()
    var fangxiangMarker: Marker? = null
    val deviceListMarker: MutableList<Marker> = ArrayList()

    private val mViewModel: DeviceViewModel by viewModels()
    private val mMsgViewModel: MsgViewModel by viewModels()

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //实时位置上报
                Log.e("map", "定位成功:$amapLocation")
                phonelatLng = LatLng(amapLocation.latitude, amapLocation.longitude)
                MapHelp.phonelatLng = phonelatLng
                binding?.mapView?.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(phonelatLng, 15F))
                var fangxiangBitmap: Bitmap? = null

                if (fangxiangBitmap == null) {
                    fangxiangBitmap = BitmapFactory.decodeResource(resources, R.mipmap.fangxiang)
                }

                if (fangxiangMarker != null) {
                    fangxiangMarker?.remove()
                }
                fangxiangMarker = binding.mapView.map.addMarker(
                    MarkerOptions().position(phonelatLng).anchor(0.5f, 0.5f)
                        .icon(BitmapDescriptorFactory.fromBitmap(fangxiangBitmap))
                )
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e(
                    "map", "location Error, ErrCode:" + amapLocation.errorCode + ", errInfo:" + amapLocation.errorInfo
                )
            }
        }
    }

    override fun onCreateViewBind(savedInstanceState: Bundle?) {
        super.onCreateViewBind(savedInstanceState)
        mapLifecycle = MapLifecycle(binding.mapView, savedInstanceState)
        lifecycle.addObserver(mapLifecycle!!)
    }

    override fun lazyLoadData() {
        binding.apply {

            //团队选择
            btnTeam.setOnClickListener {
                teamList?.find { it.teamId == teamId }?.isSelect = true
                TeamListPopup(mActivity, teamList) {
                    setBottomViewGone()
                    teamId = it
                    if (teamId.isNotEmpty()) {
                        btnTeam.setImageResource(R.mipmap.map_team_checked)
                        loadTeamDeviceList(teamId)
                    } else {
                        btnTeam.setImageResource(R.mipmap.map_team)
                        loadDeviceList()
                        Bus.post(bus_team_click, "")
                    }
                }.showPopupWindow()
            }
            if (LoginHelp.isDeviceLogin) {
                btnBack.visible()
                btnBack.setOnClickListener { mActivity.finish() }

                btnClose.gone()
                btnLoopChange.gone()
            }
            btnShowName.setOnClickListener {
                deviceListMarker.forEach {
                    it.remove()
                }
                deviceListMarker.clear()
                if (showName) {
                    btnShowNameImg.setImageResource(R.mipmap.map_name_check)
                    btnShowNameText.setTextColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.text_color_selected))
                    markerOptionsTitle.forEachIndexed { index, markerOptions ->
                        val marker = binding.mapView.map.addMarker(markerOptions)
                        marker.`object` = deviceListBean?.get(index)
                        deviceListMarker.add(marker)
                    }

                } else {
                    btnShowNameImg.setImageResource(R.mipmap.map_name)
                    btnShowNameText.setTextColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_3))
                    markerOptions.forEachIndexed { index, markerOptions ->
                        val marker = binding.mapView.map.addMarker(markerOptions)
                        marker.`object` = deviceListBean?.get(index)
                        deviceListMarker.add(marker)
                    }
                }
                showName = !showName

                deviceListMarker?.map { it.position }?.toMutableList()
                    ?.let { it1 -> MapHelp.setMapBounds(mapView, it1) }

            }

            btnMarkPoint.setOnClickListener {
                if (showMarkPoint) {
                    if (markPointList.isNullOrEmpty()) {
                        ActivityUtils.startActivity(MarkListActivity::class.java)
                        return@setOnClickListener
                    }
                    btnMarkPointImg.setImageResource(R.mipmap.map_mark_check)
                    btnMarkPointText.setTextColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.text_color_selected))
                    markPointList?.forEach {
                        val markerOptions = MapHelp.getMarkerPointUi(layoutInflater, it, false, phonelatLng)
                        val marker = binding.mapView.map.addMarker(markerOptions)
                        marker.`object` = it
                        it.isShowTitleLayout = false
                        markPointMarker.add(marker)
                    }

                    markPointList?.map { LatLng(it.pointLat, it.pointLng) }?.toMutableList()
                        ?.let { it1 -> MapHelp.setMapBounds(mapView, it1) }
                } else {
                    btnMarkPointImg.setImageResource(R.mipmap.map_mark)
                    btnMarkPointText.setTextColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_3))
                    markPointMarker.forEach {
                        it.remove()
                    }
                    markPointMarker.clear()

                }
                showMarkPoint = !showMarkPoint
            }
            btnLocation.setOnClickListener {

                when (personDogAndAll) {
                    1 -> {
                        //点击人图片
                        btnLocation.setImageResource(R.mipmap.btn_dog)
                        MapHelp.initLocation(mActivity, mLocationListener)
                        personDogAndAll = 2
                        setBottomViewGone()
                    }

                    2 -> {
                        //点击狗图片
                        btnLocation.setImageResource(R.mipmap.btn_person_dog)

                        personDogAndAll = 3
                        if (deviceListBean.isNullOrEmpty()) {
                            return@setOnClickListener
                        }
                        MapHelp.setMapBounds(binding.mapView, latLngs)
                        setBottomViewVisible()
                        deviceListBean?.get(loopPosition)?.let { it1 -> bottomSheetUiRefresh(it1) }

                    }

                    else -> {
                        //点击人狗图片
                        btnLocation.setImageResource(R.mipmap.btn_person)
                        val lngs = mutableListOf<LatLng>()
                        lngs.addAll(latLngs)
                        phonelatLng?.let { it1 -> lngs.add(it1) }
                        MapHelp.setMapBounds(binding.mapView, lngs)
                        personDogAndAll = 1
                        setBottomViewGone()
                    }
                }

            }

            btnLoopChange.setOnClickListener {
                if (deviceListBean.isNullOrEmpty()) {
                    return@setOnClickListener
                }
                if (!btnLoopChange.isVisible) {
                    return@setOnClickListener
                }
                deviceListBean?.let {
                    if (loopPosition >= (it.size - 1)) {
                        loopPosition = 0
                    } else {
                        loopPosition += 1
                    }
                }
                deviceListBean?.get(loopPosition)?.let { it1 -> bottomSheetUiRefresh(it1) }
                setBottomViewVisible()
            }

            //围栏
            btnFence.setOnClickListener {
                if (isFenceChecked) {
                    ivFence.setImageResource(R.mipmap.map_weilan_checked)
                    btnFenceText.setTextColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.text_color_selected))
                    isFenceClick = true
                    loadAreaList()
                } else {
                    ivFence.setImageResource(R.mipmap.map_weilan)
                    btnFenceText.setTextColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_3))

                    mPolygonList.forEach {
                        it.remove()
                    }
                }

                isFenceChecked = !isFenceChecked

            }


            cmd()


            btnDeviceSet.setOnClickListener {
                val bundle = Bundle()
                bundle.putSerializable("DeviceBeanContent", DeviceHelp.selectDeviceBeanContent)
                ActivityUtils.startActivity(bundle, DeviceSetActivity::class.java)

            }
            btnMode.setOnClickListener {
                ActivityUtils.startActivity(ModeSetListActivity::class.java)
            }
        }

        binding.apply {

            behavior = BottomSheetBehavior.from(bottomLayoutShow)
            var bottomMagin = 70
            if (LoginHelp.isDeviceLogin) {
                bottomMagin = 0
                behavior?.halfExpandedRatio = 0.47F
            }
            val offset = ScreenUtils.getScreenHeight() - SizeUtils.dp2px((bottomMagin + 688).toFloat())
            if (offset > 0) {
                //todo 暂时写死
                behavior?.expandedOffset = offset
            }

//            behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
            setBottomViewGone()
            behavior?.addBottomSheetCallback(object : BottomSheetCallback() {
                override fun onStateChanged(bottomSheet: View, newState: Int) {
                    if (newState == BottomSheetBehavior.STATE_EXPANDED) {


                    } else if (newState == BottomSheetBehavior.STATE_HALF_EXPANDED) {

                    } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {

                    }
                }

                override fun onSlide(bottomSheet: View, slideOffset: Float) {
                    //175+142+8  0.33
                    Log.e("slideOffset", "slideOffset: " + slideOffset)
                    btnLeftView.translationY = -(slideOffset * SizeUtils.dp2px(488F) + SizeUtils.dp2px(200F))
                    val value = 1 - (slideOffset - 0.33F) * 2 / 0.66F
                    btnLeftView.alpha = value
                    rightView.alpha = value
                    btnTeam.alpha = value
                }
            })

            btnMsg.setOnClickListener {
                ActivityUtils.startActivity(MsgActivity::class.java)
            }
            MapHelp.initLocation(mActivity, mLocationListener)
            btnDeviceService.setOnClickListener {
                if (DeviceHelp.isShare()) {
//                    customShowLong("共享设备,不可操作")
                    return@setOnClickListener
                }
                ActivityUtils.startActivity(FlowDetailActivity::class.java)

            }


            btnDeviceGuiJi.setOnClickListener {
                ActivityUtils.startActivity(TrackQueryActivity::class.java)
            }
            btnTime.setOnClickListener {
                TimeSelectPopup(mActivity).apply {
                    showPopupWindow()
                }

            }
            btnVoice.setOnClickListener {
                ActivityUtils.startActivity(VoiceActivity::class.java)

            }
            btnMapType.setOnClickListener {
                MapSelectPopup(mActivity, mapView.map.mapType) {
                    mapView.map.mapType = it
                }.showPopupWindow()
            }
            ClickUtils.expandClickArea(btnClose, SizeUtils.dp2px(10F))
            btnClose.setOnClickListener {
                setBottomViewGone()
                MapHelp.setMapBounds(binding.mapView, latLngs)

            }



            mapView.map.setOnMarkerClickListener {
                if (it.`object` != null) {

                    if (it.`object` is PointBean) {
                        val pointBean = it.`object` as PointBean
                        if (pointBean.isShowTitleLayout) {
                            MapPopup(mActivity).apply {
                                showPopupWindow()
                                mapClick(pointBean.pointLat, pointBean.pointLng)
                            }
                            return@setOnMarkerClickListener true
                        }
                        val find = markPointMarker.find { it.`object` == pointBean }
                        find?.remove()
                        val markerOptions =
                            MapHelp.getMarkerPointUi(layoutInflater, it.`object` as PointBean, true, phonelatLng)
                        val marker = binding.mapView.map.addMarker(markerOptions)
                        pointBean.isShowTitleLayout = true
                        marker.`object` = pointBean
                        markPointMarker.add(marker)


                    } else {
//                        DeviceHelp.selectDeviceBeanContent = it.`object` as DeviceBeanContent

                        setBottomViewVisible()
                        bottomSheetUiRefresh(it.`object` as DeviceBeanContent)
                    }
                }
                // 返回 true 则表示接口已响应事件，否则返回false
                true
            }
//            MapHelp.getMarkerUi(layoutInflater, deviceBeanContent) {
//                mapView.map.addMarker(it).`object` = deviceBeanContent.imei
//            }
//            MapHelp.setMapBounds(mapView, mutableListOf(LatLng(deviceBeanContent.gaoDeLat, deviceBeanContent.gaoDeLng)))

        }
    }

    private fun MapDeviceActivityBinding.cmd() {
        btnCmdVoiceDog.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_voice_dog_dialog,
                "声音寻犬",
                "是否立即下发声音寻回？",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }
        btnCmdAlarmDog.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_alrm_dog_dialog,
                "爆闪寻犬",
                "是否立即下发爆闪寻犬？",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }
        btnCmdRing.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_ring_dialog,
                "铃声训练",
                "是否立即下发铃声训练？",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }
        btnCmdVibrate.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_vibrate_dialog,
                "震动训练",
                "是否立即下发震动训练？",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }
        btnCmdElectric.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_electric_dialog,
                "电击训练",
                "是否立即下发电击训练？",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }

        btnReset.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_voice_dog_dialog,
                "恢复出厂设置",
                "设备即将恢复出厂设置，所有数据将被重置，请提前知晓。",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }

        btnReopen.setOnClickListener {
            TipPopup2(mActivity,
                R.mipmap.cmd_voice_dog_dialog,
                "远程重启",
                "猎犬项圈定位设备即将远程重启，会短暂影响定位功能，请提前知晓。",
                "确定",
                "取消",
                {
                }

            ).showPopupWindow()
        }
    }

    override fun onResume() {
        super.onResume()
        mMsgViewModel.msgUnreadCount(hashMapOf())

        //权限重新打开
        if (phonelatLng == null) {
            mapLifecycle?.initMap()
        }
    }

    override fun loadNetData() {
        super.loadNetData()

        loadDeviceList()

        loadTeam()
        loadMarkList()

        if (!isFenceChecked) {
            loadAreaList()
        }
    }

    fun loadDeviceList() {
        mViewModel.mapDeviceList(hashMapOf())
    }

    fun loadMarkList() {
        val map = HashMap<String, Any>()
        map["pageSize"] = 9999
        map["pageNum"] = 1
        mViewModel.pointList(map)
    }

    fun loadTeam() {
        val map = HashMap<String, Any>()
        map["pageSize"] = 9999
        map["pageNum"] = 1
        mViewModel.getTeamList(map)
    }

    fun loadTeamDeviceList(teamId: String) {
        if (LoginHelp.isDeviceLogin) {
            return
        }
        val map = HashMap<String, Any>()
        map["teamId"] = teamId
        mViewModel.teamDeviceList(map)

        Bus.post(bus_team_click, teamId)
    }

    fun loadAreaList() {
        val map = HashMap<String, Any>()
//        map["deviceId"] = deviceId
        mViewModel.areaList(map)
    }


    override fun observe() {
        super.observe()
        Bus.observe<String>(bus_device_info_modify, this) {
            loadNetData()
        }
        //团队
        Bus.observe<String>(bus_team_refresh, this) {
            loadTeam()
        }
        //标记点
        Bus.observe<String>(bus_mark_refresh, this) {
            loadMarkList()
        }
        //围栏
        Bus.observe<String>(bus_fence_refresh, this) {
            if (!isFenceChecked) {
                isFenceClick = false
                loadAreaList()
            }
        }
        //围栏列表
        mViewModel.fenceBean.observe(this) {
            mPolygonList.forEach {
                it.remove()
            }
            mPolygonList.clear()
            it.content.forEachIndexed { index, fenceBeanContent ->
                val stringList = fenceBeanContent?.coordinate?.split(";")
                val areaLatLngs: MutableList<LatLng> = ArrayList()
                stringList?.forEach {
                    if (!it.isNullOrEmpty()) {
                        val latLng = LatLng(it.split(",")[0].toDouble(), it.split(",")[1].toDouble())
                        areaLatLngs.add(latLng)
                    }
                }
                drawLine(areaLatLngs)
            }

            lifecycleScope.launch {
                delay(500)
                val list = mPolygonList.flatMap { it.points }.toMutableList()
                MapHelp.setMapBounds(binding.mapView, list)
            }

            if (mPolygonList.isNullOrEmpty()) {
                if (isFenceClick) {
                    ActivityUtils.startActivity(DeviceFenceListActivity::class.java)
                }
            }

        }

        //设备列表
        mViewModel.deviceListBean.observe(this) {
            deviceListMarker.forEach {
                it.remove()
            }
            deviceListMarker.clear()
            markerOptionsTitle.clear()
            markerOptions.clear()
            latLngs.clear()
//            binding.mapView.map.clear(true)

            val beanContents = it.content?.toMutableList()
            if (beanContents.isNullOrEmpty()) {
                //防止空指针判断问题
                deviceListBean = null
                setBottomViewGone()
            } else {
                deviceListBean = beanContents
            }
            if (!beanContents.isNullOrEmpty()) {
                if (binding.bottomLayoutShow.isVisible) {
                    //设备修改 展示后刷新ui
                    val find = deviceListBean?.find { it.deviceId == DeviceHelp.selectDeviceBeanContent.deviceId }
                    if (find == null) {
                        setBottomViewGone()
                    } else {
                        bottomSheetUiRefresh(find)
                    }
                }
                forMarker(0, beanContents!!) {
                    markerOptions.forEachIndexed { index, markerOptions ->
                        val marker = binding.mapView.map.addMarker(markerOptions)
                        marker.`object` = beanContents?.get(index)
                        latLngs.add(markerOptions.position)
                        deviceListMarker.add(marker)
                    }

                    if (isLoadNetFinish) {
                        MapHelp.setMapBounds(binding.mapView, latLngs)
                    }
                }
                forMarkerTitle(0, beanContents) {}
                isLoadNetFinish = true
            }
        }


        //团队列表
        mViewModel.mTeamDetailList.observe(this) {
            teamList = it?.content

            if (teamList?.find { it.teamId == teamId } == null) {
                if (teamId.isNotEmpty()) {
                    teamId = ""
                    binding.btnTeam.setImageResource(R.mipmap.map_team)
                    loadDeviceList()
                }
            } else {
                if (teamId.isNotEmpty()) {
                    loadTeamDeviceList(teamId)
                }
            }
            if (teamList.isNullOrEmpty()) {
                binding.btnTeam.gone()
            } else {
                binding.btnTeam.visible()
            }

        }

        //标记点
        mViewModel.mPointBean.observe(this) {
            markPointList = it.content
            markPointMarker.forEach {
                it.remove()
            }
            markPointMarker.clear()
            if (!showMarkPoint) {
                markPointList?.forEach {
                    val markerOptions = MapHelp.getMarkerPointUi(layoutInflater, it, false, phonelatLng)
                    val marker = binding.mapView.map.addMarker(markerOptions)
                    marker.`object` = it
                    it.isShowTitleLayout = false
                    markPointMarker.add(marker)
                }

//                markPointList?.map { LatLng(it.pointLat, it.pointLng) }?.toMutableList()
//                    ?.let { it1 -> MapHelp.setMapBounds(binding.mapView, it1) }
            }
        }


        mMsgViewModel.msgUnReadCountBean.observe(this) {
            binding.apply {
                msgOval.visibleOrGone(it.content > 0)
            }
        }
    }

    fun forMarkerTitle(index: Int, beanContents: MutableList<DeviceBeanContent>, callback: (() -> Unit)) {
        if (index < beanContents.size) {
            lifecycleScope.launch {
                delay(1000)
                MapHelp.getMarkerUi(layoutInflater, beanContents.get(index), true, phonelatLng) {
                    markerOptionsTitle.add(it)
                    forMarkerTitle(index + 1, beanContents, callback)
                }
            }
        } else {
            callback.invoke()
        }
    }

    fun forMarker(index: Int, beanContents: MutableList<DeviceBeanContent>, callback: (() -> Unit)) {
        if (index < beanContents.size) {
            MapHelp.getMarkerUi(layoutInflater, beanContents.get(index), false, phonelatLng) {
                markerOptions.add(it)
                forMarker(index + 1, beanContents, callback)
            }
        } else {
            callback.invoke()
        }
    }

    private fun fragmentFinish() {
        if (mActivity is MapDeviceDetailActivity) {
            mActivity.finish()
        } else {
            (mActivity as AppCompatActivity).supportFragmentManager.popBackStack()
        }
    }


    private val mPolygonList = mutableListOf<Polygon>()


    fun setBottomViewGone() {
//        if (!LoginHelp.isDeviceLogin) {
        binding.coordinatorLayout.setPadding(0, 0, 0, 0)
//        }
        binding.bottomLayoutShow.gone()
        binding.btnLeftView.translationY = 0F
    }

    fun setBottomViewVisible() {
        if (binding.bottomLayoutShow.isVisible) {
            return
        }
//        if (!LoginHelp.isDeviceLogin) {
        binding.coordinatorLayout.setPadding(0, 0, 0, SizeUtils.dp2px(25F))
//        }
        var bottomMagin = 25
//        if (LoginHelp.isDeviceLogin) {
//            bottomMagin = 0
//        }
        binding.btnLeftView.translationY = SizeUtils.dp2px(-(175F + bottomMagin) - 142 - 8).toFloat()
        behavior?.state = BottomSheetBehavior.STATE_HALF_EXPANDED
        binding.bottomLayoutShow.visible()
    }


    fun bottomSheetUiRefresh(deviceBeanContent: DeviceBeanContent) {
        DeviceHelp.selectDeviceBeanContent = deviceBeanContent
        binding.apply {
            if (DeviceHelp.isShare()) {
                btnDeviceService.invisible()
            } else {
                btnDeviceService.visible()
            }
        }

        if (deviceBeanContent.compositeDetailStatus == 5) {
            TipPopup(mActivity,
                R.mipmap.pop_jihuo,
                "设备未激活",
                "使用监控服务，需要激活设备",
                "立即激活",
                "下次再说",
                {
                    ActivityUtils.startActivity(ServiceDetailActivity::class.java)
                    fragmentFinish()

                },
                {
                    fragmentFinish()
                }).showPopupWindow()
        } else if (deviceBeanContent.compositeDetailStatus == 6) {

            TipPopup(mActivity,
                R.mipmap.pop_jihuo,
                "设备已过期" + deviceBeanContent.expirationDay + "天",
                "您的云服务已过期" + deviceBeanContent.expirationDay + "天，为了不中断您所依赖的重要功能和优质体验，请前往充值。",
                "前往充值",
                "下次再说",
                {
                    ActivityUtils.startActivity(ServiceDetailActivity::class.java)
                    fragmentFinish()
                },
                {
                    fragmentFinish()
                }

            ).showPopupWindow()
        }

        binding.apply {

            SpanUtils.with(desc).append("该设备于")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_9))
                .append(deviceBeanContent.lastDataTime ?: "")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_3))
                .append("定位于")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_9))
                .append(deviceBeanContent.address ?: "")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_3))
                .create()


            gpsSignal.text = gpsSignalText(deviceBeanContent.gpsSignal.toInt())
            gpsSignalImageView.setImageResource(gpsSignalImg(deviceBeanContent.gpsSignal.toInt()))
            power.text = (deviceBeanContent.power ?: "0") + "%"
            powerImageView.setImageResource(powerImg(deviceBeanContent.power?.toInt() ?: 0))
            directDesc.text = deviceBeanContent.directDesc
            directDescImageView.rotation = directRotation(deviceBeanContent.directDesc).toFloat()
            speed.text = (deviceBeanContent.speed ?: "0") + "km/h"
            deviceName.text = DeviceHelp.getDeviceName(deviceBeanContent)
            ivStatus.setDeviceDetailStatus(deviceBeanContent.compositeDetailStatus)
            tvStatus.setText(deviceBeanContent.compositeDetailStatusDesc)

            ivCar.loadImageCircleCar(deviceBeanContent.dog?.dogImg)

            val latLng = LatLng(deviceBeanContent.gaoDeLat, deviceBeanContent.gaoDeLng)
            binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15F))
            val calculateLineDistance = AMapUtils.calculateLineDistance(phonelatLng, latLng);
            km.text = getKmOrM(calculateLineDistance.toInt())
        }

    }

    fun drawLine(areaLatLngs: MutableList<LatLng>) {
        val polygonOptions = PolygonOptions()
            .addAll(areaLatLngs) // latLngs是一个包含多边形所有顶点的List<LatLng>
            .fillColor(Color.parseColor("#336E4DF3"))
            .strokeColor(Color.parseColor("#6E4DF3"))
            .strokeWidth(SizeUtils.dp2px(3F).toFloat()) // 边界线宽度

        // 创建多边形填充区域
        val polygon = binding.mapView.map.addPolygon(polygonOptions)
        mPolygonList.add(polygon)


    }
}